package com.siki.salessystemoauth2server.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siki.salessystemcommon.entity.Permission;
import com.siki.salessystemcommon.entity.Role;
import com.siki.salessystemcommon.entity.User;
import com.siki.salessystemcommon.entity.exceptions.DefineException;
import com.siki.salessystemcommon.mapper.PermissionMapper;
import com.siki.salessystemcommon.mapper.RoleMapper;
import com.siki.salessystemcommon.mapper.UserMapper;
import com.siki.salessystemoauth2server.util.WebUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 自定义UserDetailService
 *
 * @Author Siki
 * @Date 2020/12/4
 */

//@Service("userDetailService")
@Service
@RequiredArgsConstructor
public class MyUserDetailService implements UserDetailsService {

    private final UserMapper userMapper;

    public static final String VERIFICATION_USER_URL = "http://gmw.dgut.edu.cn/api/center/public/index.php/index/index/checkLogin";

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 这里的token只是为了验证是否
        JSONObject requestToken = new JSONObject();
        requestToken.put("token", username);
        JSONObject httpResponseResultJson = WebUtils.sendPostWithJson(VERIFICATION_USER_URL, requestToken);
        Assert.notNull(httpResponseResultJson,"请求token验证失败");
        assert httpResponseResultJson != null;
        Integer errorCode = (Integer) httpResponseResultJson.get("error_code");
        // 如果验证结果正常,不会有error_code;
        if (null != errorCode) {
            throw new DefineException((String) httpResponseResultJson.get("msg"));
        }

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("account", "qizai");
        User member = userMapper.selectOne(userQw);
        if (member == null) {
            throw new UsernameNotFoundException(username);
        }
        return new org.springframework.security.core.userdetails.User((String) httpResponseResultJson.get("studentNumber"), member.getPassword(), grantedAuthorities);
    }
}
